package xyf.p07.binsearch;

/**
 * ClassName: P0035_SearchInsert
 * Description:
 * Author: xyf
 * Date: 9/7/22 4:13 PM
 * Version: 1.0
 **/
public class P0035_SearchInsert
{
    // 第一个大于等于目标值的
    public int searchInsert(int[] nums, int target)
    {
        int start = 0;
        int end = nums.length - 1;
        while (start <= end)
        {
            int middle = (end - start) / 2 + start;
            if (nums[middle] < target)
            {
                start = middle + 1;
            }
            else if (nums[middle] == target)
            {
                return middle;
            }
            else
            {
                if (middle == 0 || nums[middle - 1] < target)
                {
                    return middle;
                }
                else
                {
                    end = middle - 1;
                }
            }
        }
        return nums.length;
    }
}